<template>
  <t-modal
    :title="title"
    width="900px"
    :visible="visible"
    @ok="okModal()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="名称" prop="fileName">
          <a-input v-model="form.fileName" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-form-model-item label="发布时间" prop="publishDate">
          <a-date-picker
            style="width: 100%"
            v-model="form.publishDate"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-model-item>
        <a-form-model-item
          label="文件"
          prop="files"
          :rules="{
            required: true,
            message: '请选择文件',
          }"
        >
          <bjUploadFile
            :count="10"
            v-model="form.files"
            @download="downloadFile($event)"
            @change="upLoadFile($event)"
            @preview="viewFile($event)"
            @remove="removeFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          >
          </bjUploadFile>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
//附件
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
export default {
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    treeNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      form: {
        //名称
        fileName: "",
        //发布时间
        publishDate: "",
        //文件
        files: [],
      },
      rules: {
        fileName: [
          {
            required: true,
            message: "请输入名称",
          },
        ],
        publishDate: [
          {
            required: true,
            message: "请选择发布时间",
          },
        ],
      },
      //项目
      projectSoucre: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData", "userInfo"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    title() {
      let { operateType } = this;
      switch (Number(operateType)) {
        case 1:
          return "新增";

        case 2:
          return "编辑";

        case 3:
          return "详情";

        default:
          return "新增";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getData() {
      let { uuid } = this.parameter;
      if (uuid) {
        this.getDetail();
      }
    },

    getDetail() {
      let { uuid } = this.parameter;
      axios
        .post(
          `/probusiness/archiveFile/getDetailByUuid?uuid=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          this.form = {
            //名称
            fileName: res.fileName,
            publishDate: res.publishDate,
            //文件
            files: JSON.parse(res?.files ?? "[]"),
          };
        })
        .catch((_) => {});
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    // 删除
    removeFile() {
      this.form.fileName = "";
    },
    //上传附件
    upLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["files"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form["files"][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form["files"][index], "url", res.url);
          let lastIdx = file.name.lastIndexOf(".");
          this.form.fileName = file.name.substring(0, lastIdx);
          this.$refs["ruleForm"].clearValidate(["fileName"]);
        })
        .catch((_) => {
          this.$set(this.form["files"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["files"][index], "loading", false);
        });
    },
    okModal() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form, treeNode, parameter } = this;
          const fileList = form.files.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          let formJosn = {
            ...form,
            files: JSON.stringify(fileList),
            directoryUuid: treeNode.uuid,
            directoryType: 5,
          };
          //编辑
          if (parameter.uuid) {
            formJosn.uuid = parameter.uuid;
            formJosn.directoryUuid = parameter.directoryUuid;
          }
          axios
            .post(`/probusiness/archiveFile/addOrUpdateFile`, formJosn, {
              headers: {
                "Content-Type": "application/json;charset=UTF-8",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.$parent.getTableData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {});
        }
      });
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //重置表单
    resetForm() {
      this.form = {
        //项目名称
        fileName: "",
        //发布时间
        publishDate: "",
        //文件
        files: [],
      };
      this.$refs.ruleForm.resetFields();
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
    .curve-modal-body {
      box-sizing: border-box;
      padding: 14px 70px 14px 40px;
      max-height: 700px;
      overflow: auto;
      .ant-form-item {
        display: flex;
        .ant-form-item-label {
          flex-shrink: 0;
          width: 100px;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
          overflow: hidden;
        }
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
